package com.miaoxie.forum.module.auth.shared.filter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CorsFilter extends OncePerRequestFilter {
    private final Log log = LogFactory.getLog(getClass());

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
//        Enumeration headerNames = request.getHeaderNames();
//        log.info("*********************info***********************");
//        log.info("URL:+++"+request.getRequestURL().toString());
//        while (headerNames.hasMoreElements()) {
//            String key = (String) headerNames.nextElement();
//            String value = request.getHeader(key);
//            log.info("key:"+key+"-------value:"+value);
//            log.info("value:"+value);
//        }
//        log.info("*********************info***********************");

//        response.addHeader("Access-Control-Allow-Origin", "*");
//        response.addHeader("Access-Control-Allow-Methods",
//                "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        String a = request.getHeader("Origin");
//        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
//        response.addHeader("Access-Control-Allow-Headers",
//                "origin, content-type, accept, x-requested-with, sid, mycustom, smuser");

        // 如果存在自定义的header参数，需要在此处添加，逗号分隔
        response.addHeader("Access-Control-Allow-Headers", "authorization,Origin,"
                + "No-Cache,X-Requested-With,"
                + "If-Modified-Since,Pragma,Last-Modified,Cache-Control,Expires,"
                + "Content-Type,X-E4M-With,token,username,password");

        filterChain.doFilter(request, response);
    }

}
